package com.mongodb.config;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent;
import org.springframework.stereotype.Component;

@Component
public class BeforeConvertListener extends AbstractMongoEventListener<Object> {

    @Override
    public void onBeforeSave(BeforeSaveEvent<Object> event){
        Document d = event.getDocument();
        if(d==null){
            return;
        }
        Object _id = d.get("_id");
        if (_id==null){
            event.getDocument().put("_id", new ObjectId().toString());
        } else if (_id instanceof ObjectId) {
            event.getDocument().put("_id", _id.toString());
        }
    }

}
